package com.star.eastern.blee.fragments

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.ToggleButton
import com.star.eastern.blee.BleeApplication
import com.star.eastern.blee.BlueToothActivty
import com.star.eastern.blee.MainActivity
import com.star.eastern.blee.R
import com.star.eastern.blee.customview.HdmiViewItem
import com.star.eastern.blee.utils.Tripple7BluetoothCommandProtocol
import com.star.eastern.blee.utils.Tripple7BluetoothCommandProtocol.Companion.dialog
import com.tangula.android.utils.ApplicationUtils
import com.tangula.android.utils.SharedPreferencesUtils
import com.tangula.android.utils.ToastUtils
import java.util.*
import kotlin.math.ceil


class ScanPage : Fragment() {



    private var scannerBtn: ToggleButton? = null
    var rvDeviceList: RecyclerView? = null
    val infoList = ArrayList<DeviceObject>()

    private val drawables = ArrayList<Drawable>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        drawables.clear()
        drawables.add(resources.getDrawable(R.drawable.deviceitem1))
        drawables.add(resources.getDrawable(R.drawable.deviceitem2))
        drawables.add(resources.getDrawable(R.drawable.deviceitem3))
        drawables.add(resources.getDrawable(R.drawable.deviceitem4))

    }

    override fun onCreateView(inflater: LayoutInflater, parent: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Defines the xml file for the fragment
        val rootView = inflater.inflate(R.layout.scan_layout, parent, false)

        val layoutManager = LinearLayoutManager(this.context)
        layoutManager.orientation = LinearLayoutManager.VERTICAL

        rvDeviceList = rootView.findViewById(R.id.rvDeviceList)
        rvDeviceList?.layoutManager = layoutManager
        scannerBtn = rootView.findViewById(R.id.vw_scanner)
        rvDeviceList?.adapter = DeviceViewItemAdapter(this.context ?: ApplicationUtils.APP)

        return rootView
    }

    fun initScan() {
        Tripple7BluetoothCommandProtocol.clearService()
        val rvada = rvDeviceList?.adapter as DeviceViewItemAdapter
        infoList.clear()
        rvada.notifyDataSetChanged()

        val btact = this.activity as BlueToothActivty

        if (BleeApplication.i == 1) {
            btact.finish()
            System.exit(0)
        }

        btact.listBlueToothDeviceSet { res ->
            addDevice2List(res)
        }
        //.forEach { addDevice2List(it, null) }

        //infoList.clear()
        scannerBtn?.setOnClickListener {
            //Log.v("console", "click start scan")
            Tripple7BluetoothCommandProtocol.disconnect()
            Tripple7BluetoothCommandProtocol.clearService()

            if (Tripple7BluetoothCommandProtocol.scanCallBack != null) {
                //Log.v("console", "click start scan--stop")
                Tripple7BluetoothCommandProtocol.stopScan()
                scannerBtn?.setText(R.string.scanbtn_text)
            } else {
                //Log.v("console", "click start scan--start")
                Tripple7BluetoothCommandProtocol.startScan { res ->
                    addDevice2List(res)
                }
                scannerBtn?.setText(R.string.scanbtn_canel_text)
            }
        }
    }

    private fun addDevice2List(sr: ScanResult) {

        val dv = sr.device

        var name = dv.name ?: dv.address
        if (name.length > 26) {
            name = name.substring(0, 26)
        }
        val dev = DeviceObject(0.0f, name, dv.address, drawables[infoList.size % drawables.size], sr)


        dev.signalSize = 10.0f + (ceil(sr.rssi.toFloat() / 255.0f * 100) / 10.0f)


        if (!infoList.contains(dev)) {
            infoList.add(dev)
            this.view?.findViewById<RecyclerView>(R.id.rvDeviceList)?.adapter?.notifyDataSetChanged()
        } else {
        }
    }

    private fun onConnetctDevice(dv: DeviceObject) {
        if (activity is MainActivity) {
            Tripple7BluetoothCommandProtocol.stopScan()
            (activity as MainActivity).onSelectDevice(dv)
        }
    }


    override fun onPause() {
        super.onPause()
        (activity as MainActivity).stopDiscovery()
    }

    override fun onDetach() {
        super.onDetach()
        (activity as MainActivity).stopDiscovery()
    }

    override fun onResume() {
        super.onResume()
        initScan()
    }


    inner class DeviceObject(
            internal var signalSize: Float,
            internal var deviceName: String,
            internal var deviceAddress: String,
            internal var signalTextDrawable: Drawable,
            internal var scanResult:ScanResult


    ) {
        override fun equals(other: Any?): Boolean {
            if (other is DeviceObject) {
                return this.deviceAddress == other.deviceAddress
            }
            return false
        }
    }

    class MyViewHolder internal constructor(view: View) : RecyclerView.ViewHolder(view) {

        var tvSignalText: TextView = view.findViewById(R.id.deviceitem_signalsize)
        val tvDeviceName: TextView = view.findViewById(R.id.deviceitem_devicename)
        val btnConnectBtn: Button = view.findViewById(R.id.deviceitem_connectbtn)

    }

    inner class DeviceViewItemAdapter(private val context: Context) :
            RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): MyViewHolder {
            val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.deviceitemview, viewGroup, false)
            return MyViewHolder(v)
        }

        @RequiresApi(Build.VERSION_CODES.KITKAT)
        override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
            val myViewHolder = viewHolder as MyViewHolder
            setDeviceName(position, myViewHolder)
            setDeviceSignal(position, myViewHolder)
            setClickListeners(position, myViewHolder)
        }

        fun setDeviceName(position: Int, holder: MyViewHolder) {
            holder.tvDeviceName.text = infoList[position].deviceName
        }

        fun setDeviceSignal(position: Int, holder: MyViewHolder) {
            holder.tvSignalText.background = infoList[position].signalTextDrawable
            holder.tvSignalText.text = (infoList[position].signalSize*10).toInt().toString()
        }

        @RequiresApi(Build.VERSION_CODES.KITKAT)
        fun setClickListeners(position: Int, holder: MyViewHolder) {
            holder.btnConnectBtn.setOnClickListener {
                try {
//                    alertDialog().dismiss()
                    val device = infoList[position]
                        Tripple7BluetoothCommandProtocol.dialog = alertDialog()
                        onConnetctDevice(device)
                } catch (ex: Exception) {
                    Log.e("console", ex.localizedMessage, ex)
                    ToastUtils.showToastResLong(R.string.can_not_open_device)
                }
            }
        }

        override fun getItemCount(): Int {
            return infoList.size
        }
    }

    @RequiresApi(Build.VERSION_CODES.KITKAT)
    private fun alertDialog(): AlertDialog {
        val builder = android.app.AlertDialog.Builder(this.activity)
        val inflater = LayoutInflater.from(Objects.requireNonNull<FragmentActivity>(this.activity))
        val v = inflater.inflate(R.layout.layout_loading, null)
        val dialog = builder.create()
        val dialogWindow = dialog.window
        dialog.show()
//        dialogWindow.setLayout(400,400)
        dialogWindow.setBackgroundDrawable(resources.getDrawable(android.R.color.transparent))
        dialogWindow.setContentView(v)
        dialogWindow.setGravity(Gravity.CENTER)
        return dialog
    }

}